(function() {
	require(['jquery', 'dynamicTable', 'box', 'form', 'confirm', 'select2'], function(jquery, dynamicTable, box) {
		/**
		 * contentNav:次级导航的id，用次级导航id作为宿主元素，在里面添加数据
		 */
		var reportObj = $('#contentNav').data('provinceState'),	//如果没有值，返回的是 'undefined'
			reportId = "", type="", rowData = {}, targetPhaseList=[], //defaultData = {}, orgName = "",
			i = 0, j=0, targetPhaseListLen = 0;
		/**
		 * 如果直接进入申报表，没有基础数据，所以要判断
		 */
		if(reportObj != null && reportObj != 'undefined') {
			//存放上传资金分配表路径
			$('#uploadFundTable').data('filePath', rowData.filePath);
			//说明:从列表来,有数据，
			reportId = reportObj['reportId'];	//report表中记录的唯一标识
			type = reportObj['type'];	//参数类型
			rowData = reportObj['rowdata'];	//整个report表的数据
			targetPhaseList = rowData['targetPhaseList'];	//目标和指标的集合targetNameOfImplphase
			
			if(type == 'reCreate') {	//重新填写，需要把reportId置空
				
			}else if(type == 'edit') {	//直接生成一张表
				$('#reportForm').form('load',rowData);//给表格添加数据
				$('#addTargetOfImplPhaseSpan').css("display", "");//添加实施期按钮显示
				projectNameSelect('create_project', 'update_project');	//传入的参数为select的id
				updateAttributeSelect('create_attribute', 'update_attribute');	//传入的参数为select的id
				targetAttributeSelect('create_project', 'create_attribute'); //工程名称id，项目名称id
				bindClickEvent('submitBaseInfo', {'formDataFunc': formDataFunc}, updateBaseInfo);//绑定更新基础信息事件
				bindClickEvent('addTargetOfImplPhase', {
					dynamicTableFun: dynamicTable
				}, addTargetOfImplPhase);	//绑定添加实施期目标事件
				bindClickEvent('provinceCreateTarget', {}, addClickToLitteAddBtn);//给创建实施期目标各个小的添加按钮添加点击事件
				bindClickEvent('provinceUpdateTarget', {}, addClickToLitteAddBtn);//给更新实施期目标各个小的添加按钮添加点击事件
				bindClickEvent('reportManage', {
					getTargetOfImplPhaseFun: getTargetOfImplPhaseFun,
					getAunnalTargetsFun: getAunnalTargetsFun,
					getIndexesFun: getIndexesFun,
					addIndexToProvinceReportFun: addIndexToProvinceReportFun,
					dynamicTableFun: dynamicTable,
					resetFun: resetFun
				}, save);//给保存按钮添加事件
				
				//绑定修改实施期目标事件
				bindClickEvent('target_list', {
					setUpdateValueToReportReferenceFun: setUpdateValueToReportReference,
					addIndexToProvinceReportFun: addIndexToProvinceReportFun,
					dynamicTableFun: dynamicTable
				}, updateTargetOfImplPhase);
				
				//绑定更新实施期目标按钮
				bindClickEvent('reportManageUpdate', {
					getUpdateTargetOfImplPhaseFun: getUpdateTargetOfImplPhaseFun,
					getAunnalTargetsFun: getAunnalTargetsFun,
					getUpdateIndexesFun: getUpdateIndexesFun,
					addIndexToProvinceReportFun: addIndexToProvinceReportFun,
					dynamicTableFun: dynamicTable,
					setUpdateValueToReportReferenceFun: setUpdateValueToReportReference,
					resetUpdateFun: resetUpdateFun
				}, update);
				
				showTrsFun();	//显示实施期目标以下数据
				targetPhaseListLen = targetPhaseList.length;	//实施期目标长度
				//循环给实施期指标赋值
				for(i=0, j=0; i<targetPhaseListLen; i++) {
					if(targetPhaseList[i]['targetNameOfImplphase'] == "总体目标") {
						continue;
					}
					j++;
					addIndexToProvinceReportFun(j, targetPhaseList[i], dynamicTable);
				}
				
				uploadFundTable();
				
				//直接绑定提交事件
				bindClickEvent('uploadFundTable', {}, showUpdataModal);
				bindClickEvent('reportSubmit', 
							{'id': reportId, 
							formDataFunc: formDataFunc,
							updateBaseInfoFun: updateBaseInfoWithValidate},
							commitRequest);
				
			}else {
				return;
			}
			
		} else{
			$.ajax({
				url: 'report/retrieveReportsByDIVISIONCODE.service',
				type: 'post',
				data: {divisionCode: orange.getAppContext('ORGANIZATION')['ocode']},
				success: function(data) {
					var resultData = data? data.data: null;
					if(data.success) {
						$('#reportForm').form('load',resultData);
					}else {
						$.alert({title: '提示', content: '数据错误'});
					}
				}
			});
			//说明:直接进入
			//操作：1绑定提交基础信息按钮:如果点击，点击后
			//    2如果绑定成功，
			//bindClickEvent('submitBaseInfo', {'formDataFunc': formDataFunc}, submitBaseInfo);
		}
		
		//绑定点击事件
		function bindClickEvent(id, data, fun) {
			$('#' + id).unbind('click').bind('click', data, fun);
		}
		
		function showTrsFun() {
			$.each($("#reportForm tr"), function(i){   
				   if(i > 6){    
				      this.style.display = '';  
				   }  
			}); 
		}
		
		//ajax请求，提交基础信息
		function submitBaseInfo(evt){
			//获取数据
			var formDataFunc = evt.data.formDataFunc;
			var reportFormData = formDataFunc("reportForm");
			if(reportFormData != null && reportFormData!= false) {
				$.ajax({
					url:'report/createReport.service',
					type: 'post',
					data: reportFormData,
					success: function(data) {
						var resultData = data.data? data.data: null, id="";
						if(resultData != null && data.success) {
							id = resultData.id;
							if(id != "" && id != null && id != "undefined") {
								$('#reportForm').find('input[name="id"]').val(id);
								$('#addTargetOfImplPhaseSpan').css("display", "");
								showTrsFun();	//显示实施期目标以下数据
								$.alert({title: '提示', content: '保存成功，请点添加实施期按钮继续申报'});
							}
						} else {
							$.alert({title: '提示', content: data.errorMsg});
						}
					}
				});
			}
			return;
		}
		
		function updateBaseInfoWithValidate(formDataFunc) {
			//获取数据
			var reportFormData = formDataFunc("reportForm");
			var promise = null;
			if(reportFormData != null && reportFormData != false) {
				promise = $.ajax({
					url:'report/createReport.service',
					type: 'post',
					data: reportFormData,
					success: function(data) {
						var resultData = data.data? data.data: null, id="";
						if(resultData != null && data.success) {
							id = resultData.id;
							if(id != "" && id != null && id != "undefined") {
								//$.alert({title: '提示', content: "保存成功，可以点添加实施期按钮进行申报"});
							}
						} else {
							$.alert({title: '提示', content: data.errorMsg});
						}
					}
				});
			}
			return promise;
		}
		
		function updateBaseInfo(evt) {
			//获取数据
			var formDataFunc = evt.data.formDataFunc;
			var reportFormData = formDataFunc("reportForm");
			if(reportFormData != null && reportFormData != false) {
				$.ajax({
					url:'report/createReport.service',
					type: 'post',
					data: reportFormData,
					success: function(data) {
						var resultData = data.data? data.data: null, id="";
						if(resultData != null && data.success) {
							id = resultData.id;
							if(id != "" && id != null && id != "undefined") {
								$.alert({title: '提示', content: "保存成功，可以点添加实施期按钮进行申报"});
							}
						} else {
							$.alert({title: '提示', content: data.errorMsg});
						}
					}
				});
			}
			return;
		}
		
		//申报表基础信息
		function formDataFunc() {
			var submitData = $('#' + 'reportForm').form('getFormData',{id: 'reportForm'});
				//实施期金额
			var fundsOfImplPhase = parseInt(submitData.fundsOfImplPhase? submitData.fundsOfImplPhase: 0),
				//实施期金额:其中中央补助
				centralGrantsOfImplPhase = parseInt(submitData.centralGrantsOfImplPhase? submitData.centralGrantsOfImplPhase: 0),
				//实施期金额:地方金额
				localGovernOfImplPhase = parseInt(submitData.localGovernOfImplPhase? submitData.localGovernOfImplPhase: 0),
				//年度金额
				annualFunds = parseInt(submitData.annualFunds? submitData.annualFunds: 0),
				//年度金额:其中中央补助
				centralGrantsOfAnnualFunds = parseInt(submitData.centralGrantsOfAnnualFunds? submitData.centralGrantsOfAnnualFunds: 0),
				//年度金额:地方金额
				localGovernOfAnnualFunds = parseInt(submitData.localGovernOfAnnualFunds? submitData.localGovernOfAnnualFunds: 0),
				year = $.trim(submitData.year);
			//年度是具体标识不能为空
			if(year == "" || year == null || year == 'undefined') {
				$.alert({title: '提示', content: "年度不能为空"});
				return false;
			}
			//判断实施期金额
			if(fundsOfImplPhase != centralGrantsOfImplPhase + localGovernOfImplPhase || fundsOfImplPhase == 0) {
				$.alert({title: '提示', content: "实施期金额填报不正确"});
				return false;
			}
			//判断年度金额
			if(annualFunds != centralGrantsOfAnnualFunds + localGovernOfAnnualFunds || annualFunds == 0) {
				$.alert({title: '提示', content: "年度金额填报不正确"});
				return false;
			}
			
			if(fundsOfImplPhase < annualFunds){
				$.alert({title: '提示', content: "年度金额不允许大于实施期金额"});
				return false;
			}
			return submitData;
		}
		
		function addTargetOfImplPhase(evt) {
			var funList = evt.data, dynamicTable = funList.dynamicTableFun;
			dynamicTable.deleteTrNextTrList("createTableFirstTr");
			$('#creatTable').append(dynamicTable.addTableAfterClearTable());
			var modal = $('#createModal');
			modal.modal({backdrop: "static"});
		}
		
		function updateTargetOfImplPhase(evt) {
			var funList = evt.data, 
				setUpdateValueToReportReferenceFun = funList.setUpdateValueToReportReferenceFun,
				dynamicTableFun = funList.dynamicTableFun,
				addIndexToProvinceReportFun = funList.addIndexToProvinceReportFun;
			var e = $(evt.target)[0], tagName = e.tagName, id = "", cls = "", $e = $(e), sourceFlag = "";
			if(tagName == 'A') {
				id = $e.attr('data-id')? $e.attr('data-id'): "";
				sourceFlag = $e.parent().find(".sourceFlagRed").html();
				if(!orange.strIsBlank(id)){
					//向数据库请求数据
					$.ajax({
						url: 'targetsOfImplPhase/retrieveTargetsOfImplPhaseById.service',
						type: 'post',
						data: {id: id},
						success: function(data) {
							var resultData = data.data? data.data: null;
							if(resultData != null && data.success) {
								dynamicTable.deleteTrNextTrList("updateTableFirstTr");
								if(sourceFlag == "默认") {
									$('#updateTable').append(dynamicTableFun.addUpdateTableAfterClearTable());
								} else if(sourceFlag == "自定义") {
									$('#updateTable').append(dynamicTableFun.addTableAfterClearTable());
								}
								setUpdateValueToReportReferenceFun(resultData);
								$('#updateModal').modal({backdrop: "static"});
							}
						}
					});
				} else {
					$.alert({title: '提示', content: '实施期目标的id不存在'});
				}
			} else if(tagName == 'I') {
				id = $e.parent().find('a').attr('data-id');
				cls = $e.attr('class');
				sourceFlag = $e.parent().find('.sourceFlagRed')[0].innerHTML;
				if(sourceFlag == '默认') {
					$.alert({title: '提示', content: '此实施期目标为指定目标，不能删除'});
					return;
				}
				if(cls.indexOf('delete-target') > -1) {
					$.ajax({
						url: 'targetsOfImplPhase/deleteTargetsOfImplPhaseById.service',
						type: 'post',
						data: {id: id, reportId: $('#reportId').val()},
						success: function(data) {
							var resultData = data? data.data: [], i = 0, j = 0, len = 0;
							if(data.success) {
								len = resultData.length;
								if(len > 0 ) {
									$.alert({title: '提示', content: '实施期目标删除成功'});
									$('#target_list').empty();
									$('#aunnal_target_list').empty();
									$('#tdOuterTable').empty();
									$('#tdOuterTable').append(dynamicTableFun.getOnlyTable());
									for(i=0,j=0; i<len; i++) {
										if(resultData[i]['targetNameOfImplphase'] == "总体目标") {
											continue;
										}
										j++;
										addIndexToProvinceReportFun(j, resultData[i], dynamicTableFun);
									}
								}
							} else {
								if(!data.success) {
									$.alert({title: '提示', content:data.errorMsg});
									return;
								} else {
						        	$.alert({title: '提示', content: '实施期目标没有删除成功'});
						        	return;
								}
							}
						}
					});
				}
			} else {
				return;
			}
		}
		
		//给各个小的添加按钮添加点击事件
		function addClickToLitteAddBtn(evt) {
			var t = evt.target, tagName = t.tagName, defaultTag = "I",
				$t = {}, cls = "", addFlag = "plus", deleteFlag = "minus",
				annualTarget = "aunnal-target", flag = -1,
				//添加时用
				boxesDiv = {}, boxes = [], boxesLen = 0, //$boxes = {},
				//删除时用
				acBox= {}, dataIndex = 0, $acBox = {}, temp = "";
			
			//如果不是I标签，不做处理
			if(tagName != defaultTag) return;
			
			$t = $(t);
			cls = $t.attr("class");

			if(cls.indexOf(addFlag)> flag) {
				if(cls.indexOf(annualTarget)> flag) {
					boxes = $t.parent().next().children();
					boxesLen = boxes.length;
					temp = $(boxes[boxesLen-1]).find('input[name=annualTargets]').val();
					temp? $(boxes[boxesLen-1]).after(targetAunnalBox(boxesLen+1)): $.alert({title: '提示', content: '请填写年度指标，再添加！！'});return;
				} else {
					boxesDiv = $t.parent().next().children()[0];
					boxes = boxesDiv.children;
					boxesLen = boxes.length;
					//添加指标的操作
					if(inputIsDone(boxes[boxesLen-1])) {
						addFun($(boxesDiv), targetBox(boxesLen+1));
					} else {
						$.alert({title: '提示', content: "请先填写当前目标或指标！"});
						return;
					}
				}
				
			} else if(cls.indexOf(deleteFlag)> flag) {
				acBox = $t.parent();
				$acBox = $(acBox);
				dataIndex = $acBox.attr('data-index');
				boxes = $acBox.nextAll();
					
				//重新排序
				if(boxes.length != 0 && cls.indexOf(annualTarget)> flag) {
					reSortAunnalTarget(boxes, dataIndex);
				} else {
					reSort(boxes, dataIndex);
				}
				//删除指标的操做
				deleteFun($acBox);
			} else {
				return;
			}
			
			//需要添加的指标单元
			function targetBox(index) {
				return '<div class="ac_box top-border" data-index="' + index + '">'
			   			+ '<label class="lr-4 span-add indexName">指标' + index + ':</label>'
			   			+ '<input class= "fill-3" name="thirdIndex"></input>'
			   			+ '<label class="lr-4 lr-w span-add">指标值:</label>'
			   			+ '<input class= "fill-4" name="indexValue"></input>'
			   			+ '<i class="fa fa-fw fa-minus-square-o" title="删除指标' + index + '" data-add="minus"></i>'
			   		+ '</div>';
			}
			
			//需要添加的年度目标
			function targetAunnalBox(index) {
				return '<div class="aunnalTargetBox top-border" data-index="' + index + '">'
						+ '<label class="lr-4 indexName">目标' + index + ':</label>'
						+ '<input class= "fill-1" name="annualTargets"></input>'
						+ '<i class="fa fa-fw fa-minus-square-o aunnal-target" title="删除年度目标' + index + '" data-add="minus"></i>'
						+ '</div>';
			}
			
			//判断指标的两个填报框：指标名，指标值
			//如果都有值，返回true；
			//其他情况返回false。
			function inputIsDone(obj) {
				var inputCol = $(obj).find('input'), i=0, 
					temp = $(obj).find('input[name="referValue"]').length,
					inputColLen = inputCol.length, ta = null, valuesLen = 0;
				for(i=0; i<inputColLen; i++) {
					ta = inputCol[i];
					$.trim($(ta).val())? (valuesLen++) : 0;
				}
				//如果一个指标没有填满指标名和指标值（共两个）不能添加指标
				if(valuesLen >= inputColLen-temp) {
					return true;
				} else {
					return false;
				}
			}
			
			//在给定的对象parentObj上，添加addObj对象
			function addFun(parentObj, addObj) {
				parentObj.append(addObj);
			}
			
			function reSort(objs, startIndex) {
				var len = objs.length, i=0, obj = {}, $obj = {}, newIndex = 0;
				for(i=0; i<len; i++) {
					obj = objs[i];
					$obj = $(obj);
					newIndex = parseInt(startIndex)+i;
					$obj.attr('data-index', newIndex);
					$obj.find('.indexName').html('指标' + newIndex + ':');
					$obj.find('i').attr('title', "删除指标" + newIndex + ':');
				}
			}
			
			function reSortAunnalTarget(objs, startIndex) {
				var len = objs.length, i=0, obj = {}, $obj = {}, newIndex = 0;
				for(i=0; i<len; i++) {
					obj = objs[i];
					$obj = $(obj);
					newIndex = parseInt(startIndex)+i;
					$obj.attr('data-index', newIndex);
					$obj.find('.indexName').html('指标' + newIndex + ':');
					$obj.find('i').attr('title', "删除年度目标" + newIndex + ':');
				}
			}
			
			function deleteFun(obj) {
				obj.remove();
			}
		}
		
		//添加自定义指标时，直接清空
		function resetFun(dynamicTable) {
			dynamicTable.deleteTrNextTrList("createTableFirstTr");
			$('#creatTable').append(dynamicTable.addTableAfterClearTable());
		}
		//修改默认实施期指标时，查询数据库中的数据重新显示
		function resetUpdateFun(dynamicTable, setUpdateValueToReportReferenceFun) {
			var targetId = $('#provinceUpdateTarget').find('input[name="targetIdOfImplphase"]').val();
			if(!orange.strIsBlank(targetId)){
				//向数据库请求数据
				$.ajax({
					url: 'targetsOfImplPhase/retrieveTargetsOfImplPhaseById.service',
					type: 'post',
					data: {id: targetId},
					success: function(data) {
						var resultData = data.data? data.data: null;
						if(resultData != null && data.success) {
							dynamicTable.deleteTrNextTrList("updateTableFirstTr");
							if($('#updateTable').append(dynamicTable.addUpdateTableAfterClearTable())){
								setUpdateValueToReportReferenceFun(resultData);
							}
						}
					}
				});
			} else {
				$.alert({title: '提示', content: '实施期目标的id不存在'});
			}
		}
		
		//处理 实施期目标'保存',会多次调用
		function save(evt) {
			var funList = evt.data,
				getTargetOfImplPhaseFun = funList.getTargetOfImplPhaseFun, 
				getAunnalTargetsFun = funList.getAunnalTargetsFun, 
				getIndexesFun = funList.getIndexesFun, 
				addIndexToProvinceReportFun = funList.addIndexToProvinceReportFun, 
				dynamicTableFun = funList.dynamicTableFun,
				resetFun = funList.resetFun;
			var target = evt.target, cls = $(target).attr('class'),
			reset = "reset", save = "save", index = -1, targetOfImplPhaseData = {};
			
			reportId = $('#reportForm').find('input[name="id"]').val();
			if(cls.indexOf(reset) > index) {
				resetFun(dynamicTableFun);
			} else if(cls.indexOf(save) > index) {
				//获取reportId， 如果reportId不存在，直接返回
				if(orange.strIsBlank($.trim(reportId))) {
		        	$.alert({title: '提示', content: '申报表没有reportId'});
					return;
				}
				targetOfImplPhaseData['reportId'] = reportId;
				if(!getTargetOfImplPhaseFun('targetOfImplPhase', targetOfImplPhaseData)) {
					return false;
				}
				getAunnalTargetsFun('provinceCreateTarget', 'aunnalTargetBox', targetOfImplPhaseData);
				getIndexesFun('provinceCreateTarget', targetOfImplPhaseData);
				
				createSaveRequest(targetOfImplPhaseData, addIndexToProvinceReportFun, dynamicTableFun);
				return true;
			} else {
				return false;
			}
		}
		
		function update(evt) {
			var funList = evt.data,
				getUpdateTargetOfImplPhaseFun = funList.getUpdateTargetOfImplPhaseFun, 
				getAunnalTargetsFun = funList.getAunnalTargetsFun, 
				getUpdateIndexesFun = funList.getUpdateIndexesFun, 
				addIndexToProvinceReportFun = funList.addIndexToProvinceReportFun, 
				dynamicTableFun = funList.dynamicTableFun,
				setUpdateValueToReportReferenceFun = funList.setUpdateValueToReportReferenceFun,
				resetUpdateFun = funList.resetUpdateFun;
			var target = evt.target, cls = $(target).attr('class'),
			reset = "reset", save = "save", index = -1, targetOfImplPhaseData = {};
			
			reportId = $('#reportForm').find('input[name="id"]').val();
			if(cls.indexOf(reset) > index) {
				resetUpdateFun(dynamicTableFun, setUpdateValueToReportReferenceFun);
			} else if(cls.indexOf(save) > index) {
				//获取reportId， 如果reportId不存在，直接返回
				if(orange.strIsBlank($.trim(reportId))) {
		        	$.alert({title: '提示', content: '申报表没有reportId'});
					return;
				}
				targetOfImplPhaseData['reportId'] = reportId;
				getUpdateTargetOfImplPhaseFun('targetOfImplPhase', targetOfImplPhaseData);
				getAunnalTargetsFun('provinceUpdateTarget', 'aunnalTargetBox', targetOfImplPhaseData);
				getUpdateIndexesFun('provinceUpdateTarget', targetOfImplPhaseData);
				
				updateSaveRequest(targetOfImplPhaseData, addIndexToProvinceReportFun, dynamicTableFun);
			} else {
				return;
			}
		}
		
		function createSaveRequest(targetOfImplPhaseData, addIndexToProvinceReportFun, dynamicTableFun) {
			//根据申报表id，保存实施期整体目标
			$.ajax({
				url: 'targetsOfImplPhase/createTargetsOfImplPhase.service',
				type: 'post',
				dataType: 'json',
				data: JSON.stringify(targetOfImplPhaseData),
				contentType : 'application/json;charset=utf-8',
				success: function(data) {
					var resultDataArr = data? data.data: [], i = 0, j = 0, resultLen = 0;
					if(data.success){
						resultLen = resultDataArr.length;
						if(resultLen > 0 ) {
							//删除已有目标和指标表格，重新生成
							$('#target_list').empty();
							$('#aunnal_target_list').empty();
							$('#tdOuterTable').empty();
							$('#tdOuterTable').append(dynamicTableFun.getOnlyTable());
							for(i=0,j=0; i<resultLen; i++) {
								if(resultDataArr[i]['targetNameOfImplphase'] == "总体目标") {
									continue;
								}
								j++;
								addIndexToProvinceReportFun(j, resultDataArr[i], dynamicTableFun);
							}
							$('#createModal').modal('hide');
						}
					}else {
						if(!data.success) {
							$.alert({title: '提示', content:data.errorMsg});
						} else {
				        	$.alert({title: '提示', content: '实施期目标没有填报成功'});
						}
					}
				}
			});
		}
		
		function updateSaveRequest(targetOfImplPhaseData, addIndexToProvinceReportFun, dynamicTableFun) {
			//根据申报表id，保存实施期整体目标
			$.ajax({
				url: 'targetsOfImplPhase/updateTargetsOfImplPhase.service',
				type: 'post',
				dataType: 'json',
				data: JSON.stringify(targetOfImplPhaseData),
				contentType : 'application/json;charset=utf-8',
				success: function(data) {
					var resultData = data? data.data: [], i = 0, j = 0, len = 0;
					if(data.success) {
						len = resultData.length;
						if(len > 0 ) {
							$.alert({title: '提示', content: '实施期目标修改成功'});
							$('#target_list').empty();
							$('#aunnal_target_list').empty();
							$('#tdOuterTable').empty();
							$('#tdOuterTable').append(dynamicTableFun.getOnlyTable());
							for(i=0,j=0; i<len; i++) {
								if(resultData[i]['targetNameOfImplphase'] == "总体目标") {
									continue;
								}
								j++;
								addIndexToProvinceReportFun(j, resultData[i], dynamicTableFun);
							}
							
							$('#updateModal').modal('hide');
						}
					} else {
						if(!data.success) {
							$.alert({title: '提示', content:data.errorMsg});
							return;
						} else {
				        	$.alert({title: '提示', content: '实施期目标没有填报成功'});
				        	return;
						}
					}
				}
			});
		}
		
		//上传资金分配方法
		function uploadFundTable() {
			//文件上传
			$("#fileUpload").fileinput({
			  language: 'zh', //设置语言  
	          uploadUrl: 'files/upload', //上传的地址  
	          allowedFileExtensions : ['pdf', 'docx', 'doc'],//接收的文件后缀  
	          showUpload: true, //是否显示上传按钮  
	          showCaption: false,//是否显示标题  
	          browseClass: "btn btn-primary", //按钮样式               
	          previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",   
	          uploadExtraData:{reportId:$('#reportId').val()}
			}).on("fileuploaded", function(event, data) {
				$('#uploadFundTable').data('filePath', data.filenames[0]);
				$.alert({title: '提示', content: '文件上传成功'});
				$('#uploadFundTableModal').modal("hide");
			});
		}
		
		function showUpdataModal() {
			$('#uploadFundTableModal').modal();
		}
		
		//提交按钮
		function commitRequest(evt) {
			var funList = evt.data, id = funList.id,
				formDataFunc = funList.formDataFunc,
				updateBaseInfoFun = funList.updateBaseInfoFun;
			if(!$('#uploadFundTable').data('filePath')) {
				$.alert({title: '提示', content: "请先上次资金分配表，然后再提交"});
				return;
			}
			updateBaseInfoFun(formDataFunc).then(test(formDataFunc, id));
			function test(formDataFunc, id) {
				//绑定提交方法
				if(confirm("申报后不能修改，确定申报吗？")) {
					$.ajax({
						url: 'report/updateReport.service',
						type: 'post',
						data : {id: id},
						success: function(data) {
							var resultData = data? data.data: null;
							if(resultData && data.success) {
					        	$.alert({title: '提示', content: "提交成功，提交后不能修改，点击查看列表可以查看申报结果"});
							} else if(data.success == false) {
					        	$.alert({title: '提示', content:data.errorMsg});
							} else {
								
							}
						}
					});
				}
			}
			
		}
		
		function projectNameSelect(addProject, updateProject) {
			$.ajax({
				url: 'projectCotegory/retieveProjectCotegorys.service',
				type: 'post',
				success: function(data) {
					var _data = data.data;
					var select2Data = $.map(_data, function (obj) {
						obj.text = obj.name; 
						obj.id = obj.id;
						return obj;
					});
					$("#" + addProject).select2({
						placeholder: "工程名称",
						allowClear: true,
						data: select2Data,
						minimumResultsForSearch: Infinity
					});
					$("#" + updateProject).select2({
						placeholder: "工程名称",
						allowClear: true,
						data: select2Data,
						minimumResultsForSearch: Infinity
					});
				}
			});
		}
		
		function updateAttributeSelect(addAttribute, updateAttribute) {
			$.ajax({
				url: 'targetAttribute/retrieveTargetAttributes.service',
				type: 'post',
				success: function(data) {
					var _data = data.data;
					var select2Data = $.map(_data, function (obj) {
						obj.text = obj.text || obj.targetAttribute; 
						obj.id = obj.id;
						return obj;
					});
					$("#" + addAttribute).select2({
						placeholder: "工程名称",
						allowClear: true,
						data: select2Data,
						minimumResultsForSearch: Infinity
					});
					$("#" + updateAttribute).select2({
						placeholder: "工程名称",
						allowClear: true,
						data: select2Data,
						minimumResultsForSearch: Infinity
					});
				}
			});
		}
		
		function targetAttributeSelect(projectId, attributeId) {
			$('#' + projectId).change(function() {
				var pcid = $("#" + projectId).val();
				$.ajax({
					url: 'targetAttribute/retrieveTargetAttributeBypcid.service',
					type: 'post',
					data: {
						pcid: pcid
					},
					success: function(data) {
						var _data = data.data;
						var select2Data = $.map(_data, function (obj) {
							  obj.text = obj.text || obj.targetAttribute; 
							  obj.id = obj.id;
							  return obj;
							});
						$("#" + attributeId).empty();
						$("#" + attributeId).select2({
							 placeholder: "项目名称",
							 allowClear: true,
							 data: select2Data,
							 minimumResultsForSearch: Infinity
						 });
					}
				});
			});
		}
		
		//获取实施期目标-目标属性
		//id:实施期目标
		function getTargetOfImplPhaseFun(id, targetOfImplPhase) {
			var targetNameOfImplphase = $('#create_attribute').select2('data')[0].text;
			var projectName = $('#create_project').val();
			var targetAttribute = $('#create_attribute').val();

			if(orange.strIsBlank($.trim(targetNameOfImplphase))) {
				$.alert({title: '提示', content: "'\"实施期目标name\"不能为空'"});
				return false;
			} else if(orange.strIsBlank($.trim(projectName))) {
				$.alert({title: '提示', content: "'\"工程名称\"不能为空'"});
				return false;
			} else if(orange.strIsBlank($.trim(targetAttribute))) {
				$.alert({title: '提示', content: "'\"项目名称\"不能为空'"});
				return false;
			} else {
				targetOfImplPhase['targetNameOfImplphase'] = targetNameOfImplphase;
				targetOfImplPhase['projectName'] = projectName;
				targetOfImplPhase['targetAttribute'] = targetAttribute;
				return true;
			}
		}
		
		//获取更新时实施期目标-目标属性
		//id:实施期目标
		function getUpdateTargetOfImplPhaseFun(id, targetOfImplPhase) {
			var targetIdOfImplphase = $('#provinceUpdateTarget').find('input[name="targetIdOfImplphase"]').val();
			var targetNameOfImplphase = $('#provinceUpdateTarget').find('input[name="targetNameOfImplphase"]').val();
			var projectName = $('#update_project').val();
			var targetAttribute = $('#update_attribute').val();

			if(orange.strIsBlank($.trim(targetIdOfImplphase))) {
				$.alert({title: '提示', content: "'\"实施期目标id\"不能为空'"});
				return;
			} else if(orange.strIsBlank($.trim(targetNameOfImplphase))) {
				$.alert({title: '提示', content: "'\"实施期目标name\"不能为空'"});
				return;
			} else if(orange.strIsBlank($.trim(projectName))) {
				$.alert({title: '提示', content: "'\"工程名称\"不能为空'"});
				return;
			} else if(orange.strIsBlank($.trim(targetAttribute))) {
				$.alert({title: '提示', content: "'\"项目名称\"不能为空'"});
				return;
			} else {
				targetOfImplPhase['id'] = targetIdOfImplphase;
				targetOfImplPhase['targetNameOfImplphase'] = targetNameOfImplphase;
				targetOfImplPhase['projectName'] = projectName;
				targetOfImplPhase['targetAttribute'] = targetAttribute;
			}
		}
		
		//获取年度目标
		//年度目标的className
		function getAunnalTargetsFun(id, cls, targetOfImplPhase) {//aunnalTargetBox
			var aunnalTargetBoxes = $('#' + id).find('.' + cls), annualTargetDatalist = [],
				i=0, len=aunnalTargetBoxes.length, annualTargetName = "";//annualTargets
			for(i=0; i<len; i++) {
				annualTargetName = $.trim($(aunnalTargetBoxes[i]).find('input[name="annualTargets"]').val());
				if(!orange.strIsBlank(annualTargetName)) {
					annualTargetDatalist.push({'annualTargets': annualTargetName});
				}
			}
			if(annualTargetDatalist.length != 0) {
				targetOfImplPhase['annualTargetDatalist'] = annualTargetDatalist;
			}
		}
		
		//循环获取指标实体
		//id:整体的id
		function getIndexesFun(id, targetOfImplPhase) {
			var targetBoxes = $('#' + id + ' .targetBox'), i = 0, targetLen = targetBoxes.length,
				j=0, indexLen = 0, targetBox = {}, $tb = {}, targetIndex = "", index="", targetType ="",
				firstIndex = "", secondIndex="", thirdIndex="", indexValue="", indexes = [];
			for(i=0; i<targetLen; i++) {
				//外部的box
				targetBox = targetBoxes[i];
				targetIndex = $(targetBox).attr('data-index');
				targetType = targetIndex.substring(0,1);
				firstIndex = targetIndex.substring(2,3);
				secondIndex = targetIndex.substring(4);
				
				//原子：指标
				indexBoxes = $(targetBox).children();
				indexLen = indexBoxes.length;
				
				for(j=0; j<indexLen; j++) {
					$tb = $(indexBoxes[j]);
					index = $tb.attr('data-index');
					thirdIndex = $.trim($tb.find('input[name=thirdIndex]').val());
					indexValue = $.trim($tb.find('input[name=indexValue]').val());
					
					if(!orange.strIsBlank(thirdIndex) && !orange.strIsBlank(indexValue)) {	//指标名
						indexes.push({
							'firstIndex': firstIndex,	//一级指标
							'secondIndex': secondIndex,	//二级指标
							'thirdIndex': thirdIndex,	//三级指标
							'indexValue': indexValue,	//指标值
							'targetsOfImplPhase': "",	//所属实施期目标ID
							'targetType': targetType,	//目标类型（实施期目标：0，年度目标：1）
							'code': index //指标编码
						});
					}
				}
				
			}
			targetOfImplPhase['indexEntityList'] = indexes;
		}
		
		function getUpdateIndexesFun(id, targetOfImplPhase) {
			var targetBoxes = $('#' + id + ' .targetBox'), i = 0, targetLen = targetBoxes.length,
				indexId = "", j=0, indexLen = 0, targetBox = {}, $tb = {}, targetIndex = "", index="", targetType ="",
				firstIndex = "", secondIndex="", thirdIndex="", indexValue="", indexes = [], referValue="";
			for(i=0; i<targetLen; i++) {
				//外部的box
				targetBox = targetBoxes[i];
				targetIndex = $(targetBox).attr('data-index');
				targetType = targetIndex.substring(0,1);
				firstIndex = targetIndex.substring(2,3);
				secondIndex = targetIndex.substring(4);
				indexId = $($(targetBox).find('input[name="id"]')[0]).val();
				//原子：指标
				indexBoxes = $(targetBox).children();
				indexLen = indexBoxes.length;
				
				for(j=0; j<indexLen; j++) {
					$tb = $(indexBoxes[j]);
					index = $tb.attr('data-index');
					thirdIndex = $.trim($tb.find('input[name=thirdIndex]').val());
					referValue = $tb.find('input[name=referValue]')? $.trim($tb.find('input[name=referValue]').val()): "";
					indexValue = $tb.find('input[name=indexValue]')? $.trim($tb.find('input[name=indexValue]').val()): "";
					if(!orange.strIsBlank(thirdIndex)) {	//指标名
						indexes.push({
							'id': indexId,	//指标id
							'firstIndex': firstIndex,	//一级指标
							'secondIndex': secondIndex,	//二级指标
							'thirdIndex': thirdIndex,	//三级指标
							'indexValue': indexValue,
							'referValue': referValue,	//指标值
							'targetsOfImplPhase': "",	//所属实施期目标ID
							'targetType': targetType,	//目标类型（实施期目标：0，年度目标：1）
							'code': index //指标编码
						});
					}
				}
			}
			targetOfImplPhase['indexEntityList'] = indexes;
		}
		
		//添加实施期目标到provinceReport界面
		function addIndexToProvinceReportFun(index, objData, dynamicTableFun) {
			//分解实体类
			var targetNameOfImplphase = objData.targetNameOfImplphase? objData.targetNameOfImplphase : ""; //实施期目标名称
			var targetNameOfImplphaseId = objData.id? objData.id: "";
			//var targetAttribute =objData.targetAttribute? objData.targetAttribute: "";		//"目标属性"
			var annualTargetDatalist = objData.annualTargetDatalist?objData.annualTargetDatalist: [];	//年度目标数组
			var indexdata = objData.indexEntityList? objData.indexEntityList: [];	//指标，包括：实施期、年度
			var sourceFlag = objData.sourceFlag;
			
			//获取页面实施期目标，构造新的实施期目标，追加到页面
			var targetNameOfImplphaseObj = $($('td .target-list')[0]);
			//var implTargetindex = targetNameOfImplphaseObj.children().length + 1;
			var li = buildTargetNameOfImplphaseLi(index, targetNameOfImplphase, targetNameOfImplphaseId, sourceFlag);
			if(!orange.strIsBlank(li)) {
				targetNameOfImplphaseObj.append(li);
			}
			//获取页面现有的年度指标
			var aunnalTargetObj = $($('td .aunnal-target-list')[0]);
			var aunnalTargetIndex = aunnalTargetObj.children().length + 1;
			var aunnalTargetDiv = buildAunnalTargetDivs(aunnalTargetIndex, annualTargetDatalist);
			if(!orange.strIsBlank(aunnalTargetDiv)) {
				aunnalTargetObj.append(aunnalTargetDiv);
			}
			//构造指标，追加指标
			dynamicTable.handleIndexData(indexdata);
			
			//构造实施期目标的li标签
			function buildTargetNameOfImplphaseLi(index, targetNameOfImplphase, targetNameOfImplphaseId, sourceFlag) {
				if(orange.strIsBlank(targetNameOfImplphase)) {
					return "";
				}
				sourceFlag = sourceFlag?sourceFlag:"自定义";
				if(sourceFlag == "默认") {
					return '<li><a href="javascript:void(0)" data-id="' + targetNameOfImplphaseId + '">目标' + index 
							+ '：</a><span>' + targetNameOfImplphase //'实施期目标实施期目标'
							+ '</span>' + '(<span class="sourceFlagRed">' + sourceFlag + '</span>)';
				} else {
					return '<li><a href="javascript:void(0)" data-id="' + targetNameOfImplphaseId + '">目标' + index 
							+ '：</a><span>' + targetNameOfImplphase //'实施期目标实施期目标'
							+ '</span>' + '(<span class="sourceFlagRed">' + sourceFlag + '</span>)' 
							+ '<i class="fa fa-fw fa-minus-square-o delete-target" title="删除目标' + index + ':' + targetNameOfImplphase + '"></i>';
				}
			}
			//构造年度目标
			function buildAunnalTargetDivs(aunnalTargetIndex, annualTargetDatalist) {
				var len = annualTargetDatalist? annualTargetDatalist.length : 0, i = 0, resultStr = "";
				for(i=0; i<len; i++) {
					resultStr += '<div>目标' + parseInt(aunnalTargetIndex+i) + '： '+ annualTargetDatalist[i]['annualTargets'] + '</div>' + '\n';
				}
				return resultStr;
			}
		}
		
		//修改前，给实施期目标弹出框赋值
	    function setUpdateValueToReportReference(objData) {
	    	//分解实体类
			var targetNameOfImplphase = objData.targetNameOfImplphase? objData.targetNameOfImplphase : ""; //实施期目标名称
			var targetIdOfImplphase = objData.id? objData.id: "";
			var projectName = objData.projectName? objData.projectName: "";
			var targetAttribute =objData.targetAttribute? objData.targetAttribute: "";		//"目标属性"
			var annualTargetDatalist = objData.annualTargetDatalist?objData.annualTargetDatalist: [];	//年度目标数组
			var indexdata = objData.indexEntityList? objData.indexEntityList: [];	//指标，包括：实施期、年度
	    	
			//实施期目标只有一个，直接赋值
			$('#provinceUpdateTarget').find('input[name="targetNameOfImplphase"]').val(targetNameOfImplphase);
			$('#provinceUpdateTarget').find('input[name="targetIdOfImplphase"]').val(targetIdOfImplphase);
			$('#update_project').val(projectName).trigger("change");
			$('#update_attribute').val(targetAttribute).trigger("change");
	    	
	    	//给年度目标赋值
			var aunnalTargetDivs = buildAunnalTargetDivs(annualTargetDatalist);
			if(annualTargetDatalist.length != 0) {
				$('#annualUpdateTargetlist').empty().append(aunnalTargetDivs);
			}
	    	
	    	//给指标赋值
	    	handleIndex(indexdata);
	    	
			//构造年度目标
			function buildAunnalTargetDivs(annualTargetDatalist) {
				var len = annualTargetDatalist? annualTargetDatalist.length : 0, i = 0, resultStr = "";
				for(i=0; i<len; i++) {
					resultStr += '<div class="aunnalTargetBox" data-index="1">'
					+ '<label class="lr-4 ">目标' + (i+1) + ':</label>'
					+ '<input class= "fill-1" name="annualTargets" value="' + $.trim(annualTargetDatalist[i]['annualTargets']) + '"></input>'
					+ '</div>' + '\n';
				}
				return resultStr;
			}
			
			//构造指标
			function handleIndex(indexData) {
				//注意需要id，更新时，需要id直接更新
				var i = 0, len =indexData? indexData.length : 0, tempObj = null,
					firstIndex = "", secondIndex="", thirdIndex="",
					indexValue = "", targetType = "", referValue = "",
					outerdivClsIndex = "", //需要添加一个空格
					innerDivCls = "", //需要加一个空格
					filledConstant = "filled", notfilledConstant = "notFilled",
					outBox = {}, innerBox={}, innerBoxLen = 0, innerBoxNotFilled = {},
					$innerBoxNotFilled = {}, innerBoxNotFilledLen = 0, newBox = "";
				
				for(i = 0; i<len; i++) {
					tempObj = indexData[i];
					firstIndex = tempObj['firstIndex'];
					secondIndex = tempObj['secondIndex'];
					thirdIndex = tempObj['thirdIndex'];
					indexValue = tempObj['indexValue'];
					targetType = tempObj['targetType'];
					referValue = tempObj['referValue'];
					
					outerdivClsIndex = targetType + "_" + firstIndex + '_' + secondIndex;
					innerDivCls = 'ac_box' + notfilledConstant;
					outBox= $('#provinceUpdateTarget').find('.targetBox.' + outerdivClsIndex);
					innerBox = outBox.children();
					innerBoxLen = innerBox.length;
					
					innerBoxNotFilled = outBox.find('.ac_box.' + notfilledConstant);
					$innerBoxNotFilled = $(innerBoxNotFilled);
					innerBoxNotFilledLen = $innerBoxNotFilled.length;
					
					if(innerBoxNotFilledLen == 0) {
						//构造div
						newBox = '<div class="ac_box filled" data-index="' + parseInt(innerBoxLen + 1) + '">'
									//+'<input name="id" type="hidden" value="' + id + '"></input>'
					       		   	+ '<label class="lr-4 lr-w">指标' + parseInt(innerBoxLen + 1) + ':</label>'
					       		   	+ '<input class= "fill-3" name="thirdIndex" value="' + thirdIndex + '"></input>'
					       		   	+ '<label class="lr-4 lr-w">指标值:</label>'
								    + '<input class= "fill-4" name="indexValue" value="' + indexValue + '"></input>'
								    + '<i class="fa fa-fw fa-minus-square-o" title="删除指标' + parseInt(innerBoxLen + 1) + '" data-add="minus"></i>'
					       		   	+ '</div>';
						//添加一个新的div
						outBox.append(newBox);
					} else {
						//有notFilled的div，那就直接插入值
						//$innerBoxNotFilled.find('input[name="id"]').val(id);
						$innerBoxNotFilled.find('input[name="thirdIndex"]').val(thirdIndex);
						$innerBoxNotFilled.find('input[name="indexValue"]').val(indexValue);
						$innerBoxNotFilled.find('input[name="referValue"]').val(referValue);
						$innerBoxNotFilled.removeClass(notfilledConstant).addClass(filledConstant);
					} 
				}
			}
			
			function getDepartmentData(addIndexToProvinceReportFun) {
				$.ajax({
					url: 'report/retrieveReportForDOPAF2.service',
					type: 'post',
					success: function(data) {

						targetPhaseListLen = targetPhaseList.length;	//实施期目标长度
						//循环给实施期指标赋值
						for(i=0, j=0; i<targetPhaseListLen; i++) {
							if(targetPhaseList[i]['targetNameOfImplphase'] == "总体目标") {
								continue;
							}
							j++;
							addIndexToProvinceReportFun(j, targetPhaseList[i], dynamicTable);
						}
					}
				});
			}
	    }
		
	});
	
})();
